package es.onlysolutions.gs.web.tag;

import es.onlysolutions.arq.core.auth.IUserSettings;
import es.onlysolutions.gs.comm.utils.UserSettings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.jsp.JspException;
import java.io.IOException;


public class BackgroundTag extends GSDynamicTag
{

    private static final Log logger = LogFactory.getLog( BackgroundTag.class );

    private boolean dynamic = true; //We will try to resolve the name by default.

    public boolean isDynamic()
    {
        return dynamic;
    }

    public void setDynamic(boolean dynamic)
    {
        this.dynamic = dynamic;
    }

    public int doStartTag() throws JspException
    {
        String backGroundImage = "default-background.jpg";
        String backGroundColor = "#FFFFF";

        if( dynamic )
        {
            UserSettings user = (UserSettings) pageContext.getSession().getAttribute(IUserSettings.USER_SETTINGS_ATTRIBUTE_NAME);
            if( user != null && user.getBackgroundImageName() != null && user.getBackgroundImageName().length() > 0 )
            {
                backGroundImage = user.getBackgroundImageName();
            }
            
            if( user != null && user.getBackgroundColor() != null && user.getBackgroundColor().length() > 0 )
            {
                backGroundColor = user.getBackgroundColor();
            }
        }

        try
        {
            String bodyStyleCss = "<style type=\"text/css\" xml:space=\"preserve\">" +
                    "body {\n" +
                    "    background-image: url( \"images/" + backGroundImage + "\" );\n" +
                    "    background-color: " + backGroundColor + ";\n" +
                    "    background-repeat: no-repeat;\n" +
                    "    background-attachment: fixed;\n" +
                    "    background-position:center;\n" +
                    "}" +
                    "</style>";

            writeln( bodyStyleCss );
        }
        catch (IOException e)
        {
            logger.error("Error al escribir contenido del TAG.", e);
            throw new JspException( "Error al escribir contenido del TAG.", e );
        }

        return SKIP_BODY;
    }

}
